function dichotom_f(length, array, val) result(ip)

    use iasing_osse
    
    implicit none
    !Arguments
    integer(kind=JPI4), intent(in)     :: length
    real(kind=JPR4), intent(in)      :: array(length), val
    integer(kind=JPI4)    :: ip
    
    ! Internal variables
    integer(kind=JPI4) :: ir1, ir2, ir


    ir1 = 1
    ir2 = length

    if (val<array(1)) then
        ip = -1
        return
    else if (val>array(length)) then
        ip = -2
        return
    else if (val == array(1)) then
        ip = 1
        return
    else if (val == array(length)) then
        ip = length
        return
    else
        do while ((ir2 - ir1) > 1)
            ir = int((ir2 + ir1)/2)
            if (val > array(ir)) then
                ir1 = ir
            else
                ir2 = ir
            end if
        end do
        ip = ir1
        return
    endif

end function dichotom_f
